package com.zhaorujie.rpc.core.remoting.netty.client;

import com.zhaorujie.rpc.core.exception.RpcException;
import com.zhaorujie.rpc.core.remoting.invoker.RpcInvokerFactory;
import com.zhaorujie.rpc.core.remoting.netty.codec.NettyDecoder;
import com.zhaorujie.rpc.core.remoting.netty.codec.NettyEncoder;
import com.zhaorujie.rpc.core.remoting.params.RpcRequest;
import com.zhaorujie.rpc.core.remoting.params.RpcResponse;
import com.zhaorujie.rpc.core.serialize.RpcSerialize;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author 赵汝杰
 * @version v1.0
 * @description NettyClient
 * @date 2024/3/5
 **/
public class NettyClient {

    private final static Logger logger = LoggerFactory.getLogger(NettyClient.class);

    private EventLoopGroup workerGroup;
    private Channel channel;


    public void init(final String address, final RpcSerialize rpcSerialize, final RpcInvokerFactory rpcInvokerFactory) {
        String[] array = address.split(":");
        String ip = array[0];
        int port = Integer.parseInt(array[1]);
        this.workerGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(workerGroup)
                .channel(NioSocketChannel.class)
                // 禁用 Nagle算法
                .option(ChannelOption.TCP_NODELAY, false)
                .option(ChannelOption.SO_KEEPALIVE, true)
                // 设置连接的超时时间
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline
                                .addLast(new LoggingHandler(LogLevel.DEBUG))
                                .addLast(new NettyEncoder(RpcRequest.class, rpcSerialize))
                                .addLast(new NettyDecoder(RpcResponse.class, rpcSerialize))
                                .addLast(new NettyClientHandler(rpcInvokerFactory));
                    }
                });

        try {
            this.channel = bootstrap.connect(ip, port).sync().channel();
        } catch (InterruptedException e) {
            throw new RpcException("client connect fail", e);
        }
    }

    public void close() {
        // 判断channel是否存在兵器channel是否还存活
        if (this.channel != null && this.channel.isActive()) {
            this.channel.close().addListener(future -> {
                if (future.isSuccess()) {
                    this.workerGroup.shutdownGracefully();
                    logger.debug("xxl-rpc netty client close success.");
                } else {
                    logger.debug("xxl-rpc netty client close fail.");
                }
            });
        }
        logger.debug("xxl-rpc netty client close.");
    }

    public void send(RpcRequest rpcRequest, String address, RpcSerialize rpcSerialize, RpcInvokerFactory rpcInvokerFactory) {

    }

    public boolean isValidate() {
        if (this.channel != null) {
            return this.channel.isActive();
        }
        return false;
    }

    public Channel getChannel() {
        return channel;
    }
}
